package zcl.listener;

import zcl.pojo.Product;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;

@WebListener
public class MyApplicationListener  implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("监听器初始化");
        //得到context对象
        ServletContext servletContext = sce.getServletContext();
        //构造商品,并放入集合
        HashMap<String, Product> products = new HashMap<>();
        Product p1 = new Product("1001","蓝月壳洗衣液",35.3f,200);
        Product p2 = new Product("1002","雷碧",3.3f,150);
        Product p3 = new Product("1003","通讯录",5.3f,100);
        Product p4 = new Product("1004","哈哈瓜子",5.5f,200);
        Product p5 = new Product("1005","教训",10.2f,200);
        //放入集合
        products.put(p1.getPid(),p1);
        products.put(p2.getPid(),p2);
        products.put(p3.getPid(),p3);
        products.put(p4.getPid(),p4);
        products.put(p5.getPid(),p5);
        //将map集合放入servletContext容器
        servletContext.setAttribute("products",products);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("监听器销毁");
    }
}
